<template>
  <span :class="svgClass" :style="{ color: color }">
    <component :is="iconObj" v-if="iconSource == 'ant'" />
    <!-- <svg v-else class="svg-icon" aria-hidden="true">
      <use :xlink:href="iconObj" :fill="color" />
    </svg> -->
    <component :is="iconObj" v-else class="svg-icon" />
  </span>
</template>
<script setup lang="ts">
import { getIcons } from '@/assets/icon/index';
import { cache } from './cache.js';
const props = defineProps({
  /** 附加avic-icon类 */
  avicIconClass: { type: String, default: 'avic-icon' },
  /** 图标的svg图的名称 */
  svg: { type: String, default: '' },
  /** 图标颜色 */
  color: { type: String, default: '' }
});

const svgClass = computed(() => {
  if (props.avicIconClass) {
    return `${props.avicIconClass}`;
  }
  return 'avic-icon';
});
const iconObj = shallowRef('');
const iconSource = ref('ant');
const iconGroupList = ref(getIcons());
getIconInfo(props.svg);
// 这里需要监听svg变化，否则动态修改svg后不生效
watch(
  () => props.svg,
  (newValue) => {
    getIconInfo(newValue);
  }
);
/**
 * 获取icon信息
 * @param svgName 图标名称
 */
function getIconInfo(svgName) {
  if (svgName?.includes('avic-')) {
    loadSvgIcon(svgName);
  } else {
    // 否则ant图标
    if (svgName) {
      const svgNameLower = svgName.toLowerCase();
      // 兼容vue2 ant design 图标库，vue3图标名称默认追加outlined或filled或tone，
      if (!svgNameLower.includes('outlined') && !svgNameLower.includes('filled') && !svgNameLower.includes('tone')) {
        // 确认图标为vue2图标，手动追加-outlined保证在vue3项目中可识别
        // eslint-disable-next-line no-param-reassign
        svgName = `${svgName}-outlined`;
      }
      iconObj.value = svgName;
      iconSource.value = 'ant';
    }
  }
}
// 当svg不为空时表示自定义图标库
function loadSvgIcon(iconName: string) {
  try {
    const fileName = iconName.substring(5);
    // 动态导入SVG文件，解析目录及文件名
    const dir = iconGroupList.value.find((group) => group.iconList.includes(`avic-${fileName}`))?.dir || '';
    if (cache[`${dir}/${fileName}`]) {
      iconObj.value = cache[`${dir}/${fileName}`];
    } else {
      // 将导入的SVG文件设置为组件
      iconObj.value = defineAsyncComponent(() =>
        import(`@/assets/icon/${dir}/${fileName}.svg?component`)
          .then((icon) => icon.default)
          .catch((error) => {
            console.error(`Error loading SVG icon: ${dir}/${fileName}. `, error);
          })
      );
      cache[`${dir}/${fileName}`] = iconObj.value;
    }
    iconSource.value = 'avic';
  } catch (error) {
    console.error('Error loading SVG icon:', error);
  }
}
</script>
<style lang="less">
.svg-icon {
  width: 1.1em;
  height: 1.1em;
  fill: currentColor;
  vertical-align: -0.175em;
}
</style>
